import {IChartConfig, IChartDataFilterConfigs, ICustomFilter, IFilter, IModel} from "./type";
import {DATA_ACTION_TYPE, OperatorFilterTypes, VISUALTYPES} from "./constants";

/**
 * 封装sql数据查询条件规则
 * @param config
 */
export const buildFilterConfigs = (config: IChartConfig) => {
  const {metrics, cols, filters, orders, cache, expired} = config
  const groups = cols.map((c) => {
    // const visualType = c.visualType
    // if ([VISUALTYPES.Date].includes(visualType)) {
    //   return JSON.stringify({column: c.name, visualType: visualType, value: c.dateType})
    // }
    return c.name
  })
  let filterConfigs: IChartDataFilterConfigs = {
    groups: groups,
    aggregators: metrics.map((metric) => {
      if(metric.totalType !== 'cancel') {
        return {column: metric.name.split("@")[0], func: metric.agg, calculate: metric.calculate, totalType: metric.totalType}
      }
      return {column: metric.name.split("@")[0], func: metric.agg, calculate: metric.calculate}
    }),
    filters: filters.map((filter: any) => filter.config.sqlModel[0]),
    orders: orders,
    pageNo: 0,
    pageSize: 0,
    nativeQuery: false,
    cache,
    expired,
    flush: false,
  }
  return filterConfigs
}

/**
 * 三段式搜索过滤配置
 * @param config
 * @param filterConfigs
 * @param threeSearchVals
 */
export const threeSearchFilter = (config: IChartConfig, threeSearchVals: Array<string>, formFilters: Array<IFilter>) => {
  let filterConfigs: IChartDataFilterConfigs = buildFilterConfigs(config)
  //三段式搜索
  if (threeSearchVals && threeSearchVals.length && threeSearchVals.length == 3) {
    const date = threeSearchVals[0]
    const {customFilters} = config
    let dateFilters: Array<ICustomFilter> = []
    if (customFilters && customFilters.length) {
      dateFilters = customFilters.filter((v: any) => v.visualType == VISUALTYPES.Date)
    }
    dateFilters.map(v => {
      const filter: IFilter = {
        name: v.name,
        column: `cast(${v.name} as string)`,
        operator: OperatorFilterTypes.Regexp,
        type: "filter",
        value: `${date}`,
        sqlType: "STRING",
        action: DATA_ACTION_TYPE.filter,
        visualType: VISUALTYPES.Date,
      }
      filterConfigs.filters.push(filter)
      formFilters.push(filter)
    })
  }
  return filterConfigs
}

export const isJSON = (str: any) => {
  if (typeof str == 'string') {
    try {
      const obj = JSON.parse(str);
      if (typeof obj == 'object' && obj) {
        return true;
      } else {
        return false;
      }

    } catch (e) {
      return false;
    }
  }
  return false
}
/**
 * 获取聚合的维度字段
 * @param group
 */
export const getGroupName = (group: string) => {
  if (typeof group == 'string') {
    try {
      const obj: IModel = JSON.parse(group);
      if (typeof obj == 'object' && obj) {
        return obj.column;
      } else {
        return group;
      }

    } catch (e) {
      return group;
    }
  }
  return group
}

/**
 * 判断是否是层级的类型
 * @param visualType
 */
export const isLevelVisualType = (visualType: string | undefined) =>
  visualType && [VISUALTYPES.Department, VISUALTYPES.CostCenter, VISUALTYPES.Subject].includes(visualType)

/**
 * 判断是否是层级的字段
 * @param column
 * @param model
 */
export const isLevelVisualTypeColumn = (column: string, model: any) => {
  const modelVal: IModel = model[column]
  if (modelVal) {
    const {visualType} = modelVal
    return isLevelVisualType(visualType)
  }
  return false
}

/**
 * 获取长路径叶子节点
 * @param val
 */
export const getLastLevelVisualTypeVal = (val: string) => {
  if(!val){
    return  ''
  }
  const vals = val.split(/(-|_)/)
  return vals[vals.length - 1]
}
/**
 *
 * @param val
 */
export const getLevelVisualType = (column: string, model: any) => {
  const modelVal: IModel = model[column]
  if (modelVal) {
    return modelVal.visualType
  }
  return VISUALTYPES.String
}
/**
 *
 * @param val
 */
export const getModelTypeColumn = (column: string, model: any) => {
  const modelVal: IModel = model[column]
  if (modelVal) {
    return modelVal.modelType
  }
  return null
}

/**
 * isOr=true,是或的关系，需要合并（用正则过滤）
 * @param filters
 */
export const joinFiltersIsOr = (filters: IFilter[]) => {
  let newFilters = [...filters]
  const isOrFilters = filters.filter(f => f.isOr)
  const names = Array.from(new Set(isOrFilters.map(f => f.name)))
  names.map(name => {
    const filterIn: IFilter[] = isOrFilters.filter(f => f.name == name)
    let lastIdx = 0
    filters.map((v,idx)=>{
      if(v.name == name && v.isOr){
        lastIdx = idx
      }
    })
    const values: string[] = filterIn.map(f => f.value)
    let filter: IFilter = {...filterIn[0]}
    filter.value = values.join("|")
    filter.isOr = false
    newFilters[lastIdx] = filter
  })
  return newFilters.filter(v=>!v.isOr)
}
/**
 * 下钻的路径，只取最后一次下钻的值（后端也做了）,有下钻的，筛选一定最后是按下钻的为准
 * @param filters
 */
export const joinFiltersDrills = (filters: IFilter[]) => {
  //获取所有非下钻路径的值
  let noDrillsFilters = filters.filter(f => f.action != DATA_ACTION_TYPE.drills || f.isCustomFilter)
  //获取所有下钻的值
  const drillsFilters = filters.filter(f => f.action == DATA_ACTION_TYPE.drills && !f.isCustomFilter)
  const names = Array.from(new Set(drillsFilters.map(f => f.name)))
  names.map(name => {
    const filterIn: IFilter[] = drillsFilters.filter(f => f.name == name)
    let filter: IFilter = filterIn[filterIn.length - 1]
    noDrillsFilters.push(filter)
  })
  return noDrillsFilters
}
/**
 * 加工过滤配置的值
 * @param configs
 */
export const configFilter = (configs: IChartDataFilterConfigs) => {
  let {filters} = configs
  filters = joinFiltersIsOr(filters)
  filters = joinFiltersDrills(filters)
  //过滤字段的转换（ departmentname --> regexp_extract(departmentname, '[^-|_]+$',0) ）
  filters = filters.map(f => {
    const {column,name} = f
    const filter = {...f}
    if (column) {
      filter.name = column
      filter.column = name
    }
    return filter
  })
  configs.filters = filters
  return configs
}
